package com.siruier.boss.ad.service.impl

import android.content.Context
import android.view.View
import com.bytedance.sdk.openadsdk.*
import com.siruier.boss.R
import com.siruier.boss.ad.*
import com.siruier.boss.ad.service.IAdSdkService
import com.siruier.boss.ui.AppCore
import com.siruier.boss.ui.helper.MyCustomController
import com.siruier.boss.ui.utils.Logger
import kotlinx.coroutines.suspendCancellableCoroutine
import me.jessyan.autosize.utils.ScreenUtils
import java.util.*
import kotlin.coroutines.resume

/**
 * 穿山甲广告服务
 */
class PangleSdkServiceImpl : IAdSdkService {

    private val mTTAdManager: TTAdManager by lazy { TTAdSdk.getAdManager() }

    override val adPlatform: String get() = "PANGLE"

    override suspend fun sdkInit(context: Context): Boolean = suspendCancellableCoroutine { coroutine ->
        //强烈建议在应用对应的Application#onCreate()方法中调用，避免出现content为null的异常
        TTAdSdk.init(context, TTAdConfig.Builder()
            .appId("5323740")
            .useTextureView(true) //默认使用SurfaceView播放视频广告,当有SurfaceView冲突的场景，可以使用TextureView
            .appName(context.getString(R.string.app_name))
            .titleBarTheme(TTAdConstant.TITLE_BAR_THEME_DARK)//落地页主题
            .allowShowNotify(true) //是否允许sdk展示通知栏提示,若设置为false则会导致通知栏不显示下载进度
            .debug(true) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
            .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI) //允许直接下载的网络状态集合,没有设置的网络下点击下载apk会有二次确认弹窗，弹窗中会披露应用信息
            .supportMultiProcess(false) //是否支持多进程，true支持
            .asyncInit(true) //是否异步初始化sdk,设置为true可以减少SDK初始化耗时。3450版本开始废弃~~
            .customController(MyCustomController)
            //.httpStack(new MyOkStack3())//自定义网络库，demo中给出了okhttp3版本的样例，其余请自行开发或者咨询工作人员。
            .build(),
            object : TTAdSdk.InitCallback {
                override fun success() {
                    coroutine.resume(true)
                }

                override fun fail(code: Int, p1: String?) {
                    coroutine.resume(false)
                }
            })
    }

    override fun requestPermissionIfNecessary(context: Context) = mTTAdManager.requestPermissionIfNecessary(context)

    override suspend fun loadExpressDrawNativeAd(context: Context, width: Int, height: Int): List<AdBean> {
        //step3:创建广告请求参数AdSlot,具体参数含义参考文档
        val screen = ScreenUtils.getScreenSize(context)
        val adSlot = AdSlot.Builder()
            .setCodeId("949437947")
            //期望模板广告view的size,单位dp
            .setExpressViewAcceptedSize(screen[0].toFloat(), screen[1] / AppCore.app.resources.displayMetrics.density)
            //请求广告数量为1到3条
            .setAdCount(3)
            .build()
        val mTTAdNative = mTTAdManager.createAdNative(context)
        Logger.e("开始加载")
        val ads: MutableList<TTNativeExpressAd> = mutableListOf()
        for (i in 0 until 3) {
            val adsSub = suspendCancellableCoroutine { coroutine ->
                mTTAdNative.loadExpressDrawFeedAd(adSlot, object : TTAdNative.NativeExpressAdListener {
                    override fun onError(code: Int, message: String?) {
                        Logger.e("穿山甲==>$message")
                        coroutine.resume(null)
                    }

                    override fun onNativeExpressAdLoad(ads: MutableList<TTNativeExpressAd>?) = coroutine.resume(ads)
                })
            }
            if (!adsSub.isNullOrEmpty()) {
                ads.addAll(adsSub)
            }
        }
        Logger.e("ads==>${ads}")
        return ads.mapNotNull { ad ->
            val unKey = UUID.randomUUID().toString()
            ad.setCanInterruptVideoPlay(true)
            val eiListener = MyExpressAdInteractionListener()
            ad.setExpressInteractionListener(eiListener)
            ad.render()
            var isFirst = true
            ad.setVideoAdListener(object : SimpleExpressVideoAdListener() {
                override fun onVideoAdComplete() {
                    AdSdk.adVideoCompleted?.invoke(isFirst)
                    isFirst = false
                    VideoPayTimeTimer.stopTimer(unKey)
                }
            })
            val result = suspendCancellableCoroutine { coroutine ->
                eiListener.eiListener = object : SimpleExpressAdInteractionListener() {

                    override fun onRenderFail(view: View?, msg: String?, code: Int) {
                        coroutine.resume(false)
                    }

                    override fun onRenderSuccess(view: View?, width: Float, height: Float) {
                        coroutine.resume(true)
                    }
                }
            }
            if (result) {
                AdBean(unKey, AdSdk.NATIVE_VIDEO, adPlatform, ad.expressAdView, ad).apply {
                    VideoPayTimeTimer.registerTimer(unKey, object : VideoPayTimeTimeOutListener {
                        override fun timeOut() {
                            AdSdk.adVideoCompleted?.invoke(isFirst)
                            isFirst = false
                        }
                    })
                }
            } else {
                null
            }
        }
    }

    override fun adDestroy(ad: AdBean) {
        (ad.ad as? TTNativeExpressAd)?.destroy()
    }
}

class MyExpressAdInteractionListener : TTNativeExpressAd.ExpressAdInteractionListener {
    private var onAdClickedNeed: Boolean = false
    private var onAdShowNeed: Boolean = false
    private var onRenderFailNeed: Boolean = false
    private var onRenderSuccessNeed: Boolean = false
    var eiListener: TTNativeExpressAd.ExpressAdInteractionListener? = null

    override fun onAdClicked(view: View?, type: Int) {
        if (eiListener == null) {
            onAdClickedNeed = true
        } else {
            eiListener?.onAdClicked(view, type)
        }
    }

    override fun onAdShow(view: View?, type: Int) {
        if (eiListener == null) {
            onAdShowNeed = true
        } else {
            eiListener?.onAdClicked(view, type)
        }
    }

    override fun onRenderFail(view: View?, msg: String?, code: Int) {
        if (eiListener == null) {
            onRenderFailNeed = true
        } else {
            eiListener?.onRenderFail(view, msg, code)
        }
    }

    override fun onRenderSuccess(view: View?, width: Float, height: Float) {
        if (eiListener == null) {
            onRenderSuccessNeed = true
        } else {
            eiListener?.onRenderSuccess(view, width, height)
        }
    }
}